
package com.plian.system.service.sys.message.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.plian.Tools.CollectionUtil;
import com.plian.Tools.DateUtil;
import com.plian.Tools.TokenUtil;
import com.plian.system.config.exception.MyRuntimeException;
import com.plian.system.constant.sys.FormTypeConstant;
import com.plian.system.entity.sys.BehavioralData;
import com.plian.system.entity.sys.IgnoreMessageInfo;
import com.plian.system.entity.sys.Message;
import com.plian.system.mapper.sys.MessageMapper;
import com.plian.system.model.CommonCode;
import com.plian.system.model.ListResult;
import com.plian.system.model.ObjResult;
import com.plian.system.mybatis.search.SearchEntity;
import com.plian.system.mybatis.search.SearchParamEntiy;
import com.plian.system.mybatis.support.Condition;
import com.plian.system.mybatis.support.Query;
import com.plian.system.service.sys.behavioral.IBehavioralDataService;
import com.plian.system.service.sys.message.IIgnoreMessageInfoService;
import com.plian.system.service.sys.message.IMessageService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;
import java.util.Optional;

/**
 * 首页消息列表 服务实现类
 *
 * @author jianglei
 * @since 2021-01-13
 */
@Service
@AllArgsConstructor
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message> implements IMessageService {

    private IIgnoreMessageInfoService ignoreMessageInfoService;

    private IBehavioralDataService behavioralDataService;

    @Override
    public boolean ignore(Integer id) {
        Message message = getById(id);
        if (message == null){
            throw new MyRuntimeException(new ObjResult("该消息不存在，忽略失败"));
        }
        IgnoreMessageInfo ignoreMessageInfo = IgnoreMessageInfo.builder()
                .formType(message.getFormType())
                .formTypeName(message.getFormTypeName())
                .orgId(message.getOrgId())
                .createUser(TokenUtil.getTokenUserId())
                .createTime(DateUtil.now())
                .formId(message.getFormId())
                .build();
        if (message.getFormType().equals(String.valueOf(FormTypeConstant.PM_PROPERTY_FORM))
                || message.getFormType().equals(String.valueOf(FormTypeConstant.PM_PROPERTYOUT_FORM))){
            ignoreMessageInfo.setPropertyName(message.getOrgName());
        }
        message.setIsIgnore(1);
        updateById(message);
        return ignoreMessageInfoService.save(ignoreMessageInfo);
    }

    @Override
    public ListResult<Message> list(@RequestBody Query query){
        List<SearchEntity> entityList = query.getSearch();

        if (query.getAscs()==null&&query.getDescs()==null){
            query.setDescs("message_time,id");
        }
        QueryWrapper<Message> queryWrapper = SearchParamEntiy.getQueryWrapper(
                Condition.getQueryWrapper(new Message()), entityList
        );
        String orgId = TokenUtil.getTokenOrgId();
        String userId = TokenUtil.getTokenUserId();
        queryWrapper.lambda().ne(Message::getIsIgnore, 1)
                .eq(Message::getOrgId, orgId)
                .eq(Message::getCreateUser, userId);

        IPage<Message> pages = page(Condition.getPage(query), queryWrapper);
        ListResult<Message> listResult = new ListResult<>(CommonCode.SUCCESS);
        List<Message> records = pages.getRecords();
        if (CollectionUtil.isNotEmpty(records)){
            //是否看过
            List<BehavioralData> behavioralDataList= behavioralDataService.list(Wrappers.<BehavioralData>lambdaQuery().eq(BehavioralData::getUserId, userId).eq(BehavioralData::getOrgId, orgId).eq(BehavioralData::getActionType, 1));
            if (CollectionUtil.isNotEmpty(behavioralDataList)){
                records.forEach(message ->{
                    if (Optional.ofNullable(message.getFormId()).isPresent() && Optional.ofNullable(message.getFormType()).isPresent() ){
                        Optional<BehavioralData> any = behavioralDataList.stream().filter(behavioral -> message.getFormId().equals(behavioral.getFormId()) && message.getFormType().equals(behavioral.getFormType())).findAny();
                        if (any.isPresent()){
                            message.setIsLook(1);
                        }else {
                            message.setIsLook(0);
                        }
                    }else {
                        message.setIsLook(1);
                    }
                });
            }else {
                records.forEach(message ->{
                    if (Optional.ofNullable(message.getFormId()).isPresent() && Optional.ofNullable(message.getFormType()).isPresent() ){
                        message.setIsLook(0);
                    }else {
                        message.setIsLook(1);
                    }
                });
            }
        }
        listResult.setList(records);
        listResult.setTotal(Long.valueOf(pages.getTotal()).intValue());
        return listResult;
    }
}
